import rclpy
from rclpy.node import Node
from std_msgs.msg import String
from datetime import datetime
import json

from .get_iface_ip.get_iface_ip import get_iface_ip  # 相对导入

class IfaceIpPublisher(Node):
    def __init__(self):
        super().__init__('iface_ip_publisher')

        # 参数
        self.declare_parameter('iface_name', 'ens38')   # 网卡名
        self.declare_parameter('device_name', '工控机') # 设备名称

        self.iface_name = self.get_parameter('iface_name').get_parameter_value().string_value
        self.device_name = self.get_parameter('device_name').get_parameter_value().string_value

        # Publisher：每秒发布一次 JSON 数组
        self.publisher_ = self.create_publisher(String, 'network/iface_ip', 10)
        self.timer = self.create_timer(1.0, self.timer_callback)

        self.get_logger().info(f"启动 IfaceIpPublisher, 网卡: {self.iface_name}")

    def timer_callback(self):
        ip = get_iface_ip(self.iface_name)

        # 注意这里是数组结构（list of object）
        data = [{
            "name": self.device_name,
            "ip": ip or "",
            "online": bool(ip),  # 有 IP 说明在线
            "rtt_ms": None,      # 若需要可以结合 ping_utils 获取延迟
            "last_updated": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
        }]

        # 转成 JSON 字符串
        msg = String()
        msg.data = json.dumps(data, ensure_ascii=False)
        self.publisher_.publish(msg)

        # 如需调试输出
        # self.get_logger().info(f"发布 JSON 数组: {msg.data}")

def main():
    rclpy.init()
    node = IfaceIpPublisher()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()
